const DICT_URL = 'dev/dict/';

const dictOptions = async (requestData, option, all, callback) => {
  if (!requestData['columnField']) requestData['columnField'] = 'label,code,value';
  if (!requestData['status']) requestData['status'] = '1';
  option.loading = true;
  const { code, data } = await axiosGet(DICT_URL + 'list', requestData);
  if (code === 200) {
    option.data = data;
    callback && callback(data);
  }
  if (all) option.data.unshift({ label: '全部', value: '' });
  option.loading = false;
};

const dictTreeOption = async (requestData, option, callback) => {
  option.loading = true;
  axiosGet(DICT_URL + 'treeByCode', requestData).then((res) => {
    if (res.code === 200) {
      if (Vue.isRef(option)) {
        option.value = res.data;
      }
      callback && callback(res.data);
    }
    option.loading = false;
  });
};

/* base64转文件 */
const base64toFile = (dataurl, filename) => {
  var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
};

// 上级选项
const useOptions = (data) => {
  return Vue.reactive({
    loading: false,
    data: data || [],
  });
};

/**
 * 获取上级选项
 * @param {*} url  请求地址
 * @param {*} requestData  请求数据
 * @param {ref} options 选项
 * @param {boolean} root 是否需要根节点
 * @param {Function} callback 回调函数
 */
const getSuperior = (url, requestData, options, root, callback) => {
  options.loading = true;
  axiosGet(url, requestData).then((res) => {
    if (res.data && res.data.length > 0) {
      if (options) {
        options.data = res.data;
      }
      callback && callback(res.data);
    }
    if (root) {
      options.data.unshift({ label: '顶级', value: '0', id: '0' });
    }
    options.loading = false;
  });
};
